<!-- templates/salesman/salesmanlist.html -->
<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>销售员管理 - 商店进销存管理系统</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">

    <!-- 阿里云 CDN -->
    <link href="https://unpkg.com/element-plus@2.4.3/dist/index.min.css" rel="stylesheet">
    <script src="https://unpkg.com/element-plus@2.4.3/dist/index.full.min.js"></script>

    <!-- 引入 Toastify CSS 和 JS -->
    <link href="https://cdn.jsdelivr.net/npm/toastify-js/src/toastify.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/toastify-js/src/toastify.min.js"></script>

    <!-- Tailwind 配置 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#165DFF',
                        secondary: '#0FC6C2',
                        success: '#00B42A',
                        warning: '#FF7D00',
                        danger: '#F53F3F',
                        info: '#86909C'
                    },
                    fontFamily: {
                        inter: ['Inter', 'system-ui', 'sans-serif'],
                    },
                },
            }
        }
    </script>

    <!-- 自定义工具类 -->
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }

            .sidebar-item {
                @apply flex items-center px-4 py-3 text-gray-600 hover:bg-gray-50 hover:text-primary transition-all duration-200;
            }

            .sidebar-item.active {
                @apply bg-primary/10 text-primary border-l-4 border-primary;
            }

            .card-shadow {
                @apply shadow-md hover:shadow-lg transition-shadow duration-300;
            }
        }
    </style>
</head>

<body class="font-inter bg-gray-50 min-h-screen flex flex-col">
<!-- 顶部导航栏 -->
<header class="bg-white shadow-sm">
    <div class="container mx-auto px-4 py-3 flex justify-between items-center">
        <div class="flex items-center space-x-2">
            <i class="fa fa-cubes text-primary text-2xl"></i>
            <h1 class="text-xl font-bold text-gray-800">商店进销存管理系统</h1>
        </div>

        <div class="flex items-center space-x-6">
            <div class="relative">
                <input type="text" placeholder="搜索..."
                       class="pl-10 pr-4 py-2 rounded-full border border-gray-300 focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary">
                <i class="fa fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
            </div>

            <div class="flex items-center space-x-4">
                <button class="text-gray-600 hover:text-primary transition-colors">
                    <i class="fa fa-bell-o text-xl"></i>
                </button>
                <button class="text-gray-600 hover:text-primary transition-colors">
                    <i class="fa fa-cog text-xl"></i>
                </button>
                <div class="flex items-center space-x-2 cursor-pointer">
                    <img src="https://picsum.photos/200/200" alt="用户头像" class="w-8 h-8 rounded-full object-cover">
                    <span class="text-gray-700">管理员</span>
                </div>
            </div>
        </div>
    </div>
</header>

<div class="flex flex-1 overflow-hidden">
    <!-- 侧边栏导航 -->
    <aside class="w-64 bg-white shadow-md h-[calc(100vh-64px)] overflow-y-auto transition-all duration-300">
        <nav class="py-4">
            <div class="px-4 mb-4">
                <h2 class="text-xs font-semibold text-gray-400 uppercase tracking-wider">主菜单</h2>
            </div>

            <a href="index.html" class="sidebar-item" data-path="index.html">
                <i class="fa fa-tachometer w-5 h-5 mr-3"></i>
                <span>仪表盘</span>
            </a>

            <div class="px-4 mt-6 mb-2">
                <h2 class="text-xs font-semibold text-gray-400 uppercase tracking-wider">基础信息</h2>
            </div>

            <a href="productlist.html" class="sidebar-item" data-path="productlist.html">
                <i class="fa fa-shopping-bag w-5 h-5 mr-3"></i>
                <span>商品管理</span>
            </a>

            <a href="categorylist.html" class="sidebar-item" data-path="categorylist.html">
                <i class="fa fa-th-large w-5 h-5 mr-3"></i>
                <span>类别管理</span>
            </a>

            <a href="supplierlist.html" class="sidebar-item" data-path="supplierlist.html">
                <i class="fa fa-truck w-5 h-5 mr-3"></i>
                <span>供应商管理</span>
            </a>


            <div class="px-4 mt-6 mb-2">
                <h2 class="text-xs font-semibold text-gray-400 uppercase tracking-wider">库存管理</h2>
            </div>

            <a href="warehouselist.html" class="sidebar-item" data-path="warehouselist.html">
                <i class="fa fa-archive w-5 h-5 mr-3"></i>
                <span>仓库管理</span>
            </a>

            <a href="inventorylist.html" class="sidebar-item" data-path="inventorylist.html">
                <i class="fa fa-list-alt w-5 h-5 mr-3"></i>
                <span>库存查询</span>
            </a>

            <a href="instock.html" class="sidebar-item" data-path="instock.html">
                <i class="fa fa-sign-in w-5 h-5 mr-3"></i>
                <span>入库管理</span>
            </a>

            <a href="outstock.html" class="sidebar-item " data-path="outstock.html">
                <i class="fa fa-sign-out w-5 h-5 mr-3"></i>
                <span>出库管理</span>
            </a>

            <a href="transfer.html" class="sidebar-item" data-path="transfer.html">
                <i class="fa fa-exchange w-5 h-5 mr-3"></i>
                <span>转仓管理</span>
            </a>

            <div class="px-4 mt-6 mb-2">
                <h2 class="text-xs font-semibold text-gray-400 uppercase tracking-wider">统计分析</h2>
            </div>

            <a href="../statistics/sales.html" class="sidebar-item">
                <i class="fa fa-line-chart w-5 h-5 mr-3"></i>
                <span>销售统计</span>
            </a>

            <a href="../statistics/inventory.html" class="sidebar-item">
                <i class="fa fa-pie-chart w-5 h-5 mr-3"></i>
                <span>库存分析</span>
            </a>

            <div class="px-4 mt-6 mb-2">
                <h2 class="text-xs font-semibold text-gray-400 uppercase tracking-wider">系统设置</h2>
            </div>

            <a href="salesmanlist.html" class="sidebar-item active" data-path="salesmanlist.html">
                <i class="fa fa-user-circle w-5 h-5 mr-3"></i>
                <span>用户管理</span>
            </a>


            <a href="backup.html" class="sidebar-item" data-path="system/logs.html">
                <i class="fa fa-history w-5 h-5 mr-3"></i>
                <span>数据库备份与恢复</span>
            </a>
        </nav>
    </aside>

    <!-- 主内容区域 -->
    <main class="flex-1 overflow-y-auto bg-gray-50 p-6">
        <div class="container mx-auto">
            <!-- 页面标题 -->
            <div class="mb-6">
                <h2 class="text-[clamp(1.5rem,3vw,2rem)] font-bold text-gray-800">销售员管理</h2>
                <p class="text-gray-500 mt-1">管理商店的所有销售员信息</p>
            </div>

            <!-- 操作按钮 -->
            <div class="mb-4 flex justify-between items-center">
                <button class="bg-primary text-white px-4 py-2 rounded-md hover:bg-primary/90 flex items-center" id="addSalesmanBtn">
                    <i class="fa fa-plus mr-2"></i> 添加销售员
                </button>
            </div>

            <!-- 筛选表单 -->
            <div class="mb-4 bg-white rounded-lg p-4 card-shadow">
                <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">销售员姓名</label>
                        <input type="text" id="filterName" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent" placeholder="输入销售员姓名">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">部门</label>
                        <select id="filterDepartment" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent">
                            <option value="">全部部门</option>
                            <!-- 部门选项将通过JS动态插入 -->
                        </select>
                    </div>
                    <div class="flex items-end space-x-2">
                        <button id="filterBtn" class="flex-1 bg-primary text-white px-4 py-2 rounded-md hover:bg-primary/90 flex items-center justify-center">
                            <i class="fa fa-filter mr-2"></i> 筛选
                        </button>
                        <button id="resetFilterBtn" class="px-4 py-2 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-50">
                            重置
                        </button>
                    </div>
                </div>
            </div>

            <!-- 销售员列表 -->
            <div class="bg-white rounded-xl p-6 card-shadow">
                <div class="overflow-x-auto">
                    <table class="w-full">
                        <thead>
                        <tr class="border-b border-gray-200">
                            <th class="py-3 text-left text-sm font-medium text-gray-500">销售员编号</th>
                            <th class="py-3 text-left text-sm font-medium text-gray-500">销售员姓名</th>
                            <th class="py-3 text-left text-sm font-medium text-gray-500">部门</th>
                            <th class="py-3 text-left text-sm font-medium text-gray-500">操作</th>
                        </tr>
                        </thead>
                        <tbody id="salesmanTable">
                        <!-- 数据将通过JS动态渲染 -->
                        </tbody>
                    </table>
                </div>

                <!-- 分页控件 -->
                <div class="mt-6 flex justify-between items-center">
                    <div class="text-sm text-gray-500" id="paginationInfo">共 0 条记录</div>
                    <div class="flex space-x-1" id="paginationControls">
                        <button class="px-3 py-1 border border-gray-300 rounded-md text-gray-500 hover:bg-gray-50 disabled:opacity-50" disabled>
                            <i class="fa fa-chevron-left"></i>
                        </button>
                        <button class="px-3 py-1 border border-primary bg-primary text-white rounded-md">1</button>
                        <button class="px-3 py-1 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-50">2</button>
                        <button class="px-3 py-1 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-50">3</button>
                        <button class="px-3 py-1 border border-gray-300 rounded-md text-gray-500 hover:bg-gray-50">
                            <i class="fa fa-chevron-right"></i>
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </main>
</div>

<!-- 页脚 -->
<footer class="bg-white py-4 border-t border-gray-200">
    <div class="container mx-auto px-4 text-center text-gray-500 text-sm">
        <p>© 2025 商店进销存管理系统 - 版权所有</p>
    </div>
</footer>

<!-- 销售员添加模态框 (动态创建) -->
<div id="salesmanModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden"></div>
<!-- 编辑销售员模态框 (添加到salesmanModal之后) -->
<div id="editSalesmanModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden"></div>
<!-- JavaScript -->
<script>
    // 权限检查函数
    function hasPermission(permissionCode) {
        // 从localStorage或cookie中获取用户权限列表
        const userPermissions = JSON.parse(localStorage.getItem('userPermissions') || '[]');
        return userPermissions.includes(permissionCode);
    }

    // 根据角色隐藏/展示按钮
    const applyRolePermissions = () => {
        fetch('/user-info')
            .then(response => {
                if (!response.ok) {
                    throw new Error(`获取用户信息失败: 状态码 ${response.status}`);
                }
                return response.json(); // 解析JSON格式响应
            })
            .then(data => {
                console.log('用户信息响应:', data);

                // 检查响应结构是否正确
                if (data.code !== "200" || !data.data) {
                    throw new Error(data.message || '响应数据格式错误');
                }

                const userData = data.data;
                const authorities = userData.authorities;

                // 使用正则表达式提取角色信息（假设authorities格式为"Roles:[ROLE_USER]"）
                const roles = authorities.match(/Roles:\[(.*?)\]/);
                if (roles) {
                    const roleList = roles[1].split(","); // 注意：后端返回的是ROLE_USER，无空格，使用逗号直接分割
                    console.log('用户角色:', roleList);

                    // 存储用户权限到localStorage
                    localStorage.setItem('userPermissions', JSON.stringify(roleList));

                    if (!roleList.includes("ROLE_ADMIN")) {
                        // 隐藏管理员专属按钮
                        const addSalesmanBtn = document.getElementById('addSalesmanBtn');
                        if (addSalesmanBtn) {
                            addSalesmanBtn.style.display = 'none';
                        }

                        // 隐藏需要管理员权限的按钮
                        document.querySelectorAll('[data-permission]').forEach(button => {
                            const requiredPermission = button.getAttribute('data-permission');
                            if (!hasPermission(requiredPermission)) {
                                button.style.display = 'none';
                            }
                        });
                    }
                } else {
                    console.warn('未找到角色信息，原始数据:', authorities);
                }
            })
            .catch(error => {
                console.error('获取用户信息失败:', error);
                Toastify({
                    text: '获取用户权限失败，请重新登录',
                    duration: 3000,
                    gravity: 'top',
                    position: 'right',
                    backgroundColor: '#f44336'
                }).showToast();
            });
    };

    // 确保在商品数据加载完成后再次应用权限
    const ensurePermissionsApplied = () => {
        // 如果数据是异步加载的，可能需要在数据加载完成后再次调用
        setTimeout(() => {
            applyRolePermissions();
        }, 500); // 等待500毫秒，确保数据加载完成
    };

    // 页面加载完成后初始化
    document.addEventListener('DOMContentLoaded', () => {
        initSidebarNavigation();
        setCurrentPageActive();
        loadSalesmen(); // 加载销售员数据
        loadDepartments();

        // 应用角色权限
        applyRolePermissions();

        // 确保数据加载完成后再次应用权限
        ensurePermissionsApplied();

        // 筛选按钮点击事件
        document.getElementById('filterBtn').addEventListener('click', applyFilter);

        // 重置筛选按钮点击事件
        document.getElementById('resetFilterBtn').addEventListener('click', resetFilter);

        // 绑定添加销售员按钮事件
        document.getElementById('addSalesmanBtn').addEventListener('click', showAddSalesmanForm);

        // 绑定编辑商品按钮事件
        document.addEventListener('click', (e) => {
            // 处理编辑按钮
            if (e.target.closest('.edit-btn')) {
                const button = e.target.closest('.edit-btn');
                const salesmanId = parseInt(button.getAttribute('data-id'));
                editSalesman(salesmanId);
            }

            // 处理删除按钮
            if (e.target.closest('.delete-btn')) {
                const button = e.target.closest('.delete-btn');
                const salesmanId = parseInt(button.getAttribute('data-id'));
                deleteSalesman(salesmanId);
            }
        });
    });

    let departments = []; // 全局变量存储部门数据
    // 全局变量存储当前编辑的销售员ID
    let currentEditingSalesmanId = null;
    // 全局筛选参数
    let filterParams = {
        name: '',
        department: ''
    };

    /**
     * 应用筛选条件
     */
    const applyFilter = () => {
        // 获取筛选表单的值
        filterParams = {
            name: document.getElementById('filterName').value.trim(),
            department: document.getElementById('filterDepartment').value
        };

        // 从第一页开始加载数据
        loadSalesmen(0);
    };

    /**
     * 重置筛选条件
     */
    const resetFilter = () => {
        // 重置表单
        document.getElementById('filterName').value = '';
        document.getElementById('filterDepartment').value = '';

        // 重置筛选参数
        filterParams = {
            name: '',
            department: ''
        };

        // 从第一页开始加载数据
        loadSalesmen(0);
    };

    /**
     * 加载部门数据
     */
    const loadDepartments = () => {
        // 模拟获取部门数据，实际应调用API
        departments = ['Electronics', 'Appliances', 'Furniture'];
        console.log('部门数据加载成功:', departments);

        // 填充筛选器的部门选项
        const filterDepartment = document.getElementById('filterDepartment');
        departments.forEach(department => {
            const option = document.createElement('option');
            option.value = department;
            option.textContent = department;
            filterDepartment.appendChild(option);
        });
    };

    /**
     * 显示添加销售员表单（包含部门选择）
     */
    const showAddSalesmanForm = () => {
        const modal = document.getElementById('salesmanModal');
        modal.classList.remove('hidden');

        const formContainer = document.createElement('div');
        formContainer.className = 'bg-white rounded-lg shadow-xl w-full max-w-md p-6';
        formContainer.innerHTML = `
      <div class="flex justify-between items-center mb-4">
        <h3 class="text-xl font-semibold text-gray-800">添加新销售员</h3>
        <button class="text-gray-500 hover:text-gray-700" onclick="document.getElementById('salesmanModal').classList.add('hidden')">
          <i class="fa fa-times"></i>
        </button>
      </div>
      <form id="addSalesmanForm" class="space-y-4">
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-1" for="salesmanName">销售员姓名</label>
          <input type="text" id="salesmanName" name="name" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent" required>
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-1" for="department">部门</label>
          <select id="department" name="department" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent" required>
            <option value="">请选择部门</option>
            <!-- 部门选项将通过JS动态插入 -->
          </select>
        </div>
        <div class="flex justify-end space-x-3 mt-6">
          <button type="button" class="px-4 py-2 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-50" onclick="document.getElementById('salesmanModal').classList.add('hidden')">取消</button>
          <button type="submit" class="px-4 py-2 bg-primary text-white rounded-md hover:bg-primary/90">添加销售员</button>
        </div>
      </form>
    `;

        modal.innerHTML = '';
        modal.appendChild(formContainer);

        // 动态插入部门选项
        const departmentSelect = document.getElementById('department');
        if (departments.length > 0) {
            departments.forEach(department => {
                const option = document.createElement('option');
                option.value = department;
                option.textContent = department;
                departmentSelect.appendChild(option);
            });
        } else {
            // 部门数据加载失败时的提示
            const option = document.createElement('option');
            option.value = '';
            option.textContent = '部门数据加载失败';
            option.disabled = true;
            departmentSelect.appendChild(option);
        }

        // 表单提交事件
        document.getElementById('addSalesmanForm').addEventListener('submit', (e) => {
            e.preventDefault();
            addSalesman();
        });
    };

    /**
     * 添加销售员到系统（包含部门）
     */
    const addSalesman = () => {
        // 获取表单数据（包含department）
        const formData = {
            salesmanName: document.getElementById('salesmanName').value,
            department: document.getElementById('department').value
        };

        // 验证部门是否选择
        if (!formData.department) {
            alert('请选择部门');
            return;
        }

        // 显示加载状态
        const submitButton = document.querySelector('#addSalesmanForm button[type="submit"]');
        submitButton.disabled = true;
        submitButton.innerHTML = '<i class="fa fa-spinner fa-spin mr-2"></i> 提交中...';

        // 调用API
        fetch('/salesman', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(formData),
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP错误! 状态码: ${response.status}`);
                }
                return response.json();
            })
            .then(apiResponse => {
                console.log('添加销售员API响应:', apiResponse);

                // 恢复按钮状态
                submitButton.disabled = false;
                submitButton.innerHTML = '添加销售员';

                // 处理响应
                if (apiResponse) {
                    Toastify({
                        text: "销售员添加成功",
                        duration: 3000,
                        gravity: "top",
                        position: "right",
                        backgroundColor: "#4CAF50",
                    }).showToast();
                    // 关闭表单
                    document.getElementById('salesmanModal').classList.add('hidden');
                    // 刷新销售员列表
                    loadSalesmen();
                } else {
                    const errorMsg = apiResponse && apiResponse.message
                        ? apiResponse.message
                        : '添加失败：未知错误';
                    alert(errorMsg);
                }
            })
            .catch(error => {
                console.error('添加销售员失败:', error);
                // 恢复按钮状态
                submitButton.disabled = false;
                submitButton.innerHTML = '添加销售员';
                // 显示错误信息
                alert('添加销售员失败: ' + error.message);
            });
    };

    /**
     * 从后端API加载销售员数据（支持筛选）
     */
    let currentPage = 0; // 保存当前页码（后端从0开始）
    const loadSalesmen = (page = 0) => {
        const salesmanTable = document.getElementById('salesmanTable');
        const paginationInfo = document.getElementById('paginationInfo');
        const paginationControls = document.getElementById('paginationControls');

        // 显示加载中状态
        salesmanTable.innerHTML = `
      <tr>
        <td colspan="4" class="py-4 text-center">
          <div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
          <p class="mt-2 text-gray-600">加载销售员数据中...</p>
        </td>
      </tr>
    `;

        // 构建筛选参数
        const queryParams = new URLSearchParams({
            page: page,
            size: 10,
            ...(filterParams.name && { name: filterParams.name }),
            ...(filterParams.department && { department: filterParams.department })
        });

        // 调用后端API获取销售员数据（添加筛选参数）
        fetch(`/salesman?${queryParams}`)
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP错误! 状态码: ${response.status}`);
                }
                return response.json();
            })
            .then(apiResponse => {
                console.log('API响应数据:', apiResponse);
                salesmanTable.innerHTML = '';

                // 验证响应结构
                if (!apiResponse || apiResponse.code !== "200" || !apiResponse.data) {
                    throw new Error(apiResponse?.message || 'API响应失败');
                }

                // 解构数据
                const { content: salesmen, totalElements, totalPages, pageable } = apiResponse.data;
                const currentPage = pageable.pageNumber; // 后端从0开始，前端从1开始

                // 更新分页信息
                const displayPage = currentPage + 1;
                paginationInfo.textContent = `共 ${totalElements} 条记录，当前第 ${displayPage} 页`;
                updatePaginationControls(totalPages, displayPage);

                // 处理无数据情况
                if (salesmen.length === 0) {
                    salesmanTable.innerHTML = `
          <tr>
            <td colspan="4" class="py-4 text-center text-gray-500">没有找到符合条件的销售员数据</td>
          </tr>
        `;
                    return;
                }

                // 过滤有效数据（确保有salesmanId）
                const validSalesmen = salesmen.filter(salesman =>
                    salesman && typeof salesman === 'object' && salesman.salesmanId !== undefined
                );

                if (validSalesmen.length === 0) {
                    throw new Error('所有销售员数据均无效');
                }

                // 渲染销售员数据
                validSalesmen.forEach(salesman => {
                    const row = document.createElement('tr');
                    row.className = 'border-b border-gray-100 hover:bg-gray-50';

                    // 从API数据中提取字段（含默认值处理）
                    const id = salesman.salesmanId;
                    const name = salesman.salesmanName || '未知姓名';
                    const department = salesman.department || '未知部门';

                    row.innerHTML = `
          <td class="py-3 text-sm text-gray-600">${id}</td>
          <td class="py-3 text-sm text-gray-600">${name}</td>
          <td class="py-3 text-sm text-gray-600">${department}</td>
          <td class="py-3 text-sm text-gray-600">
            <button data-id="${id}" class="edit-btn text-primary mr-2" data-permission="SALESMAN_EDIT">
              <i class="fa fa-pencil"></i> 编辑
            </button>
            <button data-id="${id}" class="delete-btn text-danger" data-permission="SALESMAN_DELETE">
              <i class="fa fa-trash"></i> 删除
            </button>
          </td>
        `;
                    salesmanTable.appendChild(row);
                });
            })
            .catch(error => {
                console.error('加载销售员数据失败:', error);
                salesmanTable.innerHTML = `
        <tr>
          <td colspan="4" class="py-4 text-center text-red-500">
            <i class="fa fa-exclamation-circle mr-2"></i> 加载销售员数据失败，请稍后重试
          </td>
        </tr>
      `;

                Toastify({
                    text: `加载销售员数据失败: ${error.message}`,
                    duration: 3000,
                    gravity: "top",
                    position: "right",
                    backgroundColor: "#f44336",
                }).showToast();
            });
        // 确保重新应用角色权限
        setTimeout(() => {
            applyRolePermissions();
        }, 100); // 等待数据加载完成

    };

    /**
     * 更新分页控件
     */
    const updatePaginationControls = (totalPages, currentPage) => {
        const controls = document.getElementById('paginationControls');
        controls.innerHTML = '';

        // 上一页按钮
        const prevBtn = document.createElement('button');
        prevBtn.className = `px-3 py-1 border border-gray-300 rounded-md text-gray-500 hover:bg-gray-50 ${currentPage === 1 ? 'opacity-50 cursor-not-allowed' : ''}`;
        prevBtn.disabled = currentPage === 1;
        prevBtn.innerHTML = '<i class="fa fa-chevron-left"></i>';
        prevBtn.addEventListener('click', () => {
            if (currentPage > 1) {
                loadSalesmen(currentPage - 2); // 转换为后端页码（前端页码-1）
            }
        });
        controls.appendChild(prevBtn);

        // 页码按钮 (显示当前页及前后两页)
        const startPage = Math.max(1, currentPage - 2);
        const endPage = Math.min(totalPages, currentPage + 2);

        for (let i = startPage; i <= endPage; i++) {
            const pageBtn = document.createElement('button');
            pageBtn.className = `px-3 py-1 border rounded-md text-gray-700 hover:bg-gray-50 ${i === currentPage ? 'border-primary bg-primary text-white' : ''}`;
            pageBtn.textContent = i;
            pageBtn.addEventListener('click', () => {
                loadSalesmen(i - 1); // 转换为后端页码（前端页码-1）
            });
            controls.appendChild(pageBtn);
        }

        // 下一页按钮
        const nextBtn = document.createElement('button');
        nextBtn.className = `px-3 py-1 border border-gray-300 rounded-md text-gray-500 hover:bg-gray-50 ${currentPage === totalPages ? 'opacity-50 cursor-not-allowed' : ''}`;
        nextBtn.disabled = currentPage === totalPages;
        nextBtn.innerHTML = '<i class="fa fa-chevron-right"></i>';
        nextBtn.addEventListener('click', () => {
            if (currentPage < totalPages) {
                loadSalesmen(currentPage); // 转换为后端页码（前端页码-1）
            }
        });
        controls.appendChild(nextBtn);
    };

    /**
     * 显示消息提示（替代ElMessage）
     */
    const showMessage = (message, type = 'success') => {
        if (window.ElementPlus && window.ElementPlus.ElMessage) {
            // 使用Element Plus的消息提示
            window.ElementPlus.ElMessage({
                message,
                type,
                duration: 3000
            });
        } else {
            // 备选方案：使用原生alert
            alert(`${type === 'success' ? '成功' : '错误'}: ${message}`);
        }
    };

    /**
     * 加载指定页码的销售员数据（新增函数，处理分页请求）
     */
    const loadSalesmenWithPage = (pageNumber) => {
        // 实际项目中应传递page参数到API
        // 示例：fetch(`/salesman?page=${pageNumber-1}&size=10`)
        // 此处仅模拟页码切换效果
        const salesmanTable = document.getElementById('salesmanTable');
        salesmanTable.innerHTML = `
      <tr>
        <td colspan="4" class="py-4 text-center">
          <div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
          <p class="mt-2 text-gray-600">加载第 ${pageNumber} 页数据中...</p>
        </td>
      </tr>
    `;

        // 模拟延迟加载（实际项目中删除此定时器，直接调用API）
        setTimeout(() => {
            // 注意：实际项目中应传递page参数（后端从0开始）
            // loadSalesmen(pageNumber - 1);
            loadSalesmen(); // 临时用全量加载模拟
        }, 500);
    };

    /**
     * 加载销售员详情
     */
    const fetchSalesmanDetails = async (salesmanId) => {
        try {
            const response = await fetch(`/salesman/${salesmanId}`);
            if (!response.ok) {
                throw new Error(`获取销售员详情失败: 状态码 ${response.status}`);
            }
            return await response.json();
        } catch (error) {
            console.error('获取销售员详情失败:', error);
            Toastify({
                text: `获取销售员详情失败: ${error.message}`,
                duration: 3000,
                gravity: "top",
                position: "right",
                backgroundColor: "#f44336",
            }).showToast();
            throw error;
        }
    };

    /**
     * 显示编辑销售员表单
     */
    const showEditSalesmanForm = (salesmanId) => {
        currentEditingSalesmanId = salesmanId;
        const modal = document.getElementById('editSalesmanModal');
        modal.classList.remove('hidden');

        const formContainer = document.createElement('div');
        formContainer.className = 'bg-white rounded-lg shadow-xl w-full max-w-md p-6';
        formContainer.innerHTML = `
      <div class="flex justify-between items-center mb-4">
        <h3 class="text-xl font-semibold text-gray-800">编辑销售员</h3>
        <button class="text-gray-500 hover:text-gray-700" onclick="document.getElementById('editSalesmanModal').classList.add('hidden')">
          <i class="fa fa-times"></i>
        </button>
      </div>
      <form id="editSalesmanForm" class="space-y-4">
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-1" for="editSalesmanName">销售员姓名</label>
          <input type="text" id="editSalesmanName" name="name" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent" required>
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-1" for="editDepartment">部门</label>
          <select id="editDepartment" name="department" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent" required>
            <option value="">请选择部门</option>
            <!-- 部门选项将通过JS动态插入 -->
          </select>
        </div>
        <div class="flex justify-end space-x-3 mt-6">
          <button type="button" class="px-4 py-2 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-50" onclick="document.getElementById('editSalesmanModal').classList.add('hidden')">取消</button>
          <button type="submit" class="px-4 py-2 bg-primary text-white rounded-md hover:bg-primary/90">保存修改</button>
        </div>
      </form>
    `;

        modal.innerHTML = '';
        modal.appendChild(formContainer);

        // 动态插入部门选项
        const departmentSelect = document.getElementById('editDepartment');
        if (departments.length > 0) {
            departments.forEach(department => {
                const option = document.createElement('option');
                option.value = department;
                option.textContent = department;
                departmentSelect.appendChild(option);
            });
        } else {
            // 部门数据加载失败时的提示
            const option = document.createElement('option');
            option.value = '';
            option.textContent = '部门数据加载失败';
            option.disabled = true;
            departmentSelect.appendChild(option);
        }

        // 加载销售员详情
        fetchSalesmanDetails(salesmanId)
            .then(salesman => {
                document.getElementById('editSalesmanName').value = salesman.salesmanName;
                document.getElementById('editDepartment').value = salesman.department;
            })
            .catch(error => {
                console.error('加载销售员详情失败:', error);
                showMessage('加载销售员详情失败，请稍后重试', 'error');
                document.getElementById('editSalesmanModal').classList.add('hidden');
            });

        // 表单提交事件
        document.getElementById('editSalesmanForm').addEventListener('submit', (e) => {
            e.preventDefault();
            saveSalesmanChanges();
        });
    };

    /**
     * 保存销售员修改
     */
    const saveSalesmanChanges = () => {
        const formData = {
            salesmanName: document.getElementById('editSalesmanName').value,
            department: document.getElementById('editDepartment').value
        };

        // 验证部门是否选择
        if (!formData.department) {
            alert('请选择部门');
            return;
        }

        // 显示加载状态
        const submitButton = document.querySelector('#editSalesmanForm button[type="submit"]');
        submitButton.disabled = true;
        submitButton.innerHTML = '<i class="fa fa-spinner fa-spin mr-2"></i> 提交中...';

        // 调用API
        fetch(`/salesman/${currentEditingSalesmanId}`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(formData),
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP错误! 状态码: ${response.status}`);
                }
                return response.json();
            })
            .then(apiResponse => {
                console.log('保存销售员修改API响应:', apiResponse);

                // 恢复按钮状态
                submitButton.disabled = false;
                submitButton.innerHTML = '保存修改';

                // 处理响应
                if (apiResponse) {
                    Toastify({
                        text: "销售员信息修改成功",
                        duration: 3000,
                        gravity: "top",
                        position: "right",
                        backgroundColor: "#4CAF50",
                    }).showToast();
                    // 关闭表单
                    document.getElementById('editSalesmanModal').classList.add('hidden');
                    // 刷新销售员列表
                    loadSalesmen();
                } else {
                    const errorMsg = apiResponse && apiResponse.message
                        ? apiResponse.message
                        : '修改失败：未知错误';
                    alert(errorMsg);
                }
            })
            .catch(error => {
                console.error('保存销售员修改失败:', error);
                // 恢复按钮状态
                submitButton.disabled = false;
                submitButton.innerHTML = '保存修改';
                // 显示错误信息
                alert('保存销售员修改失败: ' + error.message);
            });
    };

    /**
     * 删除销售员
     */
    const deleteSalesman = (salesmanId) => {
        if (confirm('确定要删除该销售员吗？')) {
            // 显示加载状态
            const rows = document.querySelectorAll('#salesmanTable tr');
            rows.forEach(row => {
                if (parseInt(row.querySelector('td:first-child').textContent) === salesmanId) {
                    row.style.opacity = 0.5;
                }
            });

            // 调用API
            fetch(`/salesman/${salesmanId}`, {
                method: 'DELETE',
            })
                .then(response => {
                    if (!response.ok) {
                        // 服务器返回错误状态码（如404、500等）
                        return response.text().then(text => {
                            throw new Error(`删除失败: ${text || response.statusText}`);
                        });
                    }
                    // 删除成功（无论响应内容如何）
                    return { success: true };
                })
                .then(() => {
                    Toastify({
                        text: "销售员删除成功",
                        duration: 3000,
                        gravity: "top",
                        position: "right",
                        backgroundColor: "#4CAF50",
                    }).showToast();
                    // 刷新销售员列表
                    loadSalesmen();
                })
                .catch(error => {
                    console.error('删除销售员失败:', error);
                    // 恢复行状态
                    rows.forEach(row => {
                        if (parseInt(row.querySelector('td:first-child').textContent) === salesmanId) {
                            row.style.opacity = 1;
                        }
                    });
                    // 显示错误信息
                    alert('删除销售员失败: ' + error.message);
                });
        }
    };

    // 侧边栏导航初始化和当前页面激活函数（需要根据实际情况实现）
    const initSidebarNavigation = () => {
        // 初始化侧边栏导航逻辑
    };

    const setCurrentPageActive = () => {
        // 设置当前页面侧边栏项为激活状态
        const currentPath = window.location.pathname.split('/').pop();
        const sidebarItems = document.querySelectorAll('.sidebar-item');
        sidebarItems.forEach(item => {
            if (item.dataset.path === currentPath) {
                item.classList.add('active');
            } else {
                item.classList.remove('active');
            }
        });
    };

    // 编辑销售员函数
    const editSalesman = (salesmanId) => {
        showEditSalesmanForm(salesmanId);
    };
</script>
</body>

</html>